package com.wuchao.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
//import com.sun.xml.internal.bind.v2.TODO;
import com.wuchao.entity.Entry;
import com.wuchao.service.EntryService;
//import com.wuchao.service.impl.Xmlimpl;
import com.wuchao.utils.BaseController;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.print.Book;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author wuchao66
 * @Date 2023/10/19 9:28
 * @PackageName:com.wuchao.controller
 * @ClassName: EntryController
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
@Controller
public class EntryController  {//控制器
//    extends BaseController
    //容器注入
    @Resource
    EntryService entryService;

//    @Resource
//    Xmlimpl xmlimpl;
//将请求映射到标注@RequestMapping注解的控制器和处理方法上
    @RequestMapping("show")//op.equals (add)
    public String show(Model model){//主推 系统传参
        //ModelAndView
        //xmlimpl.findBookstore()
        List<Entry> entryById = entryService.findEntryById(2);
        model.addAttribute("entry",entryById.get(0));
        return "main";
    }
    //ModelAndView
    @RequestMapping("{show1,show2}")//op.equals (add)
    public ModelAndView show1(){//
        ModelAndView modelAndView = new ModelAndView();
        List<Entry> entryById = entryService.findEntryById(2);
        modelAndView.addObject("entry",entryById.get(0));
        modelAndView.setViewName("main");
        return modelAndView;
    }
    //转发重定向，用别人的方法来充当内调
    @RequestMapping("tomain")//op.equals (add)
    public String tomain(){//主推 系统传参
        return "forward:show";
    }
    //异步 mc
    @RequestMapping("toajax")//op.equals (add)
    @ResponseBody//异步
    public String toajax(){//主推 系统传参
        List<Entry> entryById = entryService.findEntryById(2);
        return JSON.toJSONString(entryById);
    }
//    //封页最后的写法
//    @RequestMapping(value = "topage",method = RequestMethod.GET)//op.equals (add)
//    public String topage(Model model,
//                         @RequestParam(name = "currentPage",required = false,defaultValue = "2") int currentPage,
//                         @RequestParam(name = "pageSize",required = false,defaultValue = "3")   int pageSize,
//                         @RequestParam(name = "title",required = false,defaultValue = "")    String title,
//                         @RequestParam(name = "categoryId",required = false,defaultValue = "2")   int categoryId){//主推 系统传参
//        PageInfo<Entry> pages = entryService.findEntryAndCategoryByCONCATTitleByCategoryId(currentPage, pageSize, title, categoryId);
//        model.addAttribute("pages",pages);
//        return "main";
//    }
    //层级关系、
    @RequestMapping("toload")//op.equals (add)
    public String toload(){//主推 系统传参
        return "load/load";
    }

    //异步注册 register
    @RequestMapping("register")//op.equals (add)
    @ResponseBody//异步
    public String register(String title){//主推 系统传参
        List<Entry> list = entryService.findEntryByTitle(title);
        return list.size()>0?JSON.toJSONString("y"):JSON.toJSONString("n");
    }
    @RequestMapping("to169")//op.equals (add)
    public String to169(){//主推 系统传参
        return "toajax169";
    }

    //解决中文乱码produces={"application/json;charset=UTF-8"}
    //异步查询中文和时间 findEntryAjaxById
    @RequestMapping(value = "findEntryAjaxById", produces={"application/json;charset=UTF-8"})//op.equals (add)
   // @RequestMapping(value = "findEntryAjaxById")//op.equals (add)
    @ResponseBody//异步
    public String findEntryAjaxById(int id){//主推 系统传参
        List<Entry> entryById = entryService.findEntryById(id);
        return JSON.toJSONString(entryById.get(0));
    }

    @RequestMapping("sys/toindex")//op.equals (add)
    public String toindex1(){//主推 系统传参
        return "main";
    }
    @RequestMapping("toindex")//op.equals (add)
    public String toindex2(){//主推 系统传参
        return "main";
    }

    //去登录页面
    @RequestMapping("toload169")//op.equals (add)
    public String toload169(){//主推 系统传参
        return "load";
    }
    //loadby系统内部入参
    @RequestMapping("loadby")//op.equals (add)
    public String loadby(HttpSession session, Model model, String title , String summary){//主推 系统传参
     int i=   entryService.loadby(title, summary);
     if(i<1){
         model.addAttribute("f","账户或者密码错误");
     }else{
         session.setAttribute("user",title);
         session.setMaxInactiveInterval(60);
     }
        return i>0?"work":"load";
    }
    //注销 loadout
    @RequestMapping("loadout")//op.equals (add)
    public String loadout(HttpSession session, Model model){//主推 系统传参
        session.invalidate();
        model.addAttribute("f","注销成功");
        return "load";
    }
    //故意报错
    @RequestMapping("ex")//op.equals (add)
    public String ex(){//主推 系统传参
        try {
            int num=4;
            int s=num/0;//
        }catch (ArithmeticException arithmeticException) {
            throw  new ArithmeticException("算数异常");
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        throw  new RuntimeException("我就是玩一玩，故意报错，咋地啦+我报错是运行异常");

    }
    //模型带值
    @RequestMapping("go169")//op.equals (add)
    public String go169(@ModelAttribute("name") String name){//主推 系统传参
        return "t169";
    }
    //增加
//字符串--》date--->字符串
    @RequestMapping("addentry")//op.equals (add)
    public String addentry(Model model,String time){//主推 系统传参
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        Date date=null;
        try {
            date=  df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
       entryService.addEntryByEntry( new Entry().setCreatedate(date));
        return "t169";
    }

    //查出日期去展示
    @RequestMapping("showtime")//op.equals (add)
    public String showtime(Model model,int id){//主推 系统传参
        Entry entry = entryService.findEntryById(id).get(0);
        model.addAttribute("entry",entry);
        return "t169";
    }

    //前校验11022222222 js ajax-异步注册 qwert 和后校验
//    @GetMapping
//    @DeleteMapping
   // @RequestMapping("s303")//op.equals (add)
    //jsr 303 12388888888
    @RequestMapping("toj303")
    public String toj303(){
        return "j303/add";
    }

    @RequestMapping("byadd")
    public String byadd(@Validated Entry entry,BindingResult bindingResult){
        //后手303校验、
        if(bindingResult.hasErrors()){
            return "j303/add";
        }
        entryService.addEntryByEntry(entry);
        return "j303/work";
    }
    //跟着 @RequestMapping请求生效之前，都会做的事情
    @ModelAttribute
    public void init(Model model){//@ModelAttribute： 所标记的方法为非请求处理方法，在所有请求方法之前被调用
        System.out.println("非请求处理方法");
        //必须操作 -spring bean-渲染的骆驼法自带
        model.addAttribute("entry",new Entry());
    }


    @RequestMapping("toadd169")
    public String toadd169(@ModelAttribute("Entry") Entry entry){//主推 系统传参
        return "add";//@Validated
    }

    //去增加页面
    @RequestMapping("add1")
    public String add1(){//主推 系统传参
        return "/jsr303/toadd";//@Validated
    }
    @RequestMapping("/add")
    public String add0(){//主推 系统传参
        return "/jsr303/add";//@Validated
    }
//    @RequestMapping("/add")
//    public String add0(@ModelAttribute("Entry") Entry entry){//主推 系统传参
//        return "/jsr303/add";//@Validated
//    }
    @RequestMapping(value = "/addjs")
    public String s303( @Validated Entry entry,  BindingResult bindingResult){//主推 系统传参
        if(bindingResult.hasErrors()){
            return "/jsr303/add";
        }
        entryService.addEntryByEntry( entry);
        return "forward:add";//@Validated
    }
//    @ModelAttribute
//    public void init(Model model){//@ModelAttribute： 所标记的方法为非请求处理方法，在所有请求方法之前被调用
//        System.out.println("非请求处理方法");
//        //必须操作
//        model.addAttribute("entry",new Entry());
//    }

    //rest风格
    @RequestMapping("torest/{name}/{id}")
    public String torest(@PathVariable @ModelAttribute("name")String name,
                         @PathVariable @ModelAttribute("id")int id){//主推 系统传参
        return "rest";//@Validated
    }
    @RequestMapping("touploadfiles")
    public String touploadfiles(){//主推 系统传参
        return "uploadfiles";//@Validated
    }

    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public ModelAndView upload(
            @RequestParam(value = "files",required = false)MultipartFile [] files,
            HttpServletRequest request){
        //1老名字 新名字 //2文件大小 //3文件类型 //4新文件路径 老文件路径 io文件传输--%>
        ModelAndView modelAndView = new ModelAndView();
        //拿到文件的新路径
        String newpath=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"newUploadImages");
        //判断非空
        for(MultipartFile file : files){
            if(file!=null){
                //文件大小
                long size=file.getSize();
                if(size<5000000){
                    //文件扩展名
                    String oldname=file.getOriginalFilename();
                    //拿到文件扩展名
                    String extension = FilenameUtils.getExtension(oldname);
                    if(extension.equalsIgnoreCase("jpg") ||
                            extension.equalsIgnoreCase("png")
                            || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("pneg")){
                        String newname=System.currentTimeMillis()+ UUID.randomUUID().toString()+"_chaoge.jpg";
                        //建立新的文件传输对象
                        File filenew=new File(newpath,newname);//路名
                        //判断文件对象是否存在
                        if(!filenew.exists()){
                            filenew.mkdirs();
                        }
                        //建立文件传输 lao 传新的
                        try {
                            file.transferTo(filenew);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }modelAndView.addObject("isupload","文件传输成功");
                        modelAndView.addObject("newname",newname);
                        modelAndView.addObject("newpath",newpath);
                    }else{
                        modelAndView.addObject("error","文件格式不对");
                    }
                }else{
                    modelAndView.addObject("error","文件太大");
                }

            }else{
                modelAndView.addObject("error","文件为空");
            }
        }
        modelAndView.setViewName("uploadfiles");
        return modelAndView;
    }


    @RequestMapping("upload111")
    public String upload111(MultipartFile [] files, HttpServletRequest httpServletRequest){//头像上传
        //1 文件不能是空
        //2 文件大小不能超
        //3文件的格式不能错 jpG png  txt
        //原始文件名和后缀
        //新的文件路径 新的文件  xxx/xxxx/xx.jpg
String newname=System.currentTimeMillis()+ UUID.randomUUID().toString()+"_chaogege.jpg";
//String newpath=请求路径+ "statics"+File.separator+"newimages";
   // file.size()
     //   FilenameUtils.getExtension();
        return "rest";
    }
}
